package com.shenfa.action.upload;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.shenfa.bean.BackLetter;
import com.shenfa.bean.Person;
import com.shenfa.dao.CustomerBillDao;
import com.shenfa.dao.xml.MakeXmlDao;
import com.shenfa.service.LetterService;
import com.shenfa.util.StringUtil;

public class Upload2Action extends ActionSupport {
	@Autowired
	private MakeXmlDao makeXmlDao;
	@Autowired
	private CustomerBillDao cbDao;
	@Autowired
	private LetterService letterService;

	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(Upload2Action.class);
	private FileOutputStream fos;
	private FileInputStream fis;

	private File file;
	private String type;
	private String basepath;// 基础路径
	private HttpServletRequest request;
	private HttpServletResponse response;
	private String filename;


	/**
	 * 特殊账单上传文件
	 * 
	 * @param type
	 */
	public String execute() {
		// 判断文件目录是否存在
		request = ServletActionContext.getRequest();
		Object obj = request.getSession().getAttribute("login");
		if (null == obj)
			return null;
		Person person = (Person) obj;
		// 总数据库中获取配置
		basepath = makeXmlDao.getConfig().get("BASEPATH");
		String currentPath = basepath + person.getId();
		File outFile = new File(currentPath);
		if (!outFile.exists()) {
			outFile.mkdirs();
		}
		String filepath = "";
		if (null != type) {
			filepath = currentPath + "/" + type + ".txt";
		}
		outFile = new File(filepath);
		if (outFile.exists()) {
			outFile.delete();
		}
		try {
			if (outFile.createNewFile()) {
				fis = new FileInputStream(file);
				fos = new FileOutputStream(outFile);
				// 将上传文件的内容写入服务器
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != fis)
					fis.close();
				if (null != fos)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
				log.error(e.getMessage());
			}
		}
		this.returnMsg("{success:true,msg:'successed'}");
		return null;
	}

	/**
	 * 解析已经上传的文件存数据库
	 * 
	 * @param type
	 * @throws IOException
	 */
	public String parseFile() throws IOException {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		Object obj = request.getSession().getAttribute("login");
		if (null == obj)
			return null;
		Person person = (Person) obj;
		basepath = makeXmlDao.getConfig().get("BASEPATH");// 从数据库中取basepath
		String currentPath = basepath + person.getId() + "/";

		/*
		 * 文件类型 ATCSZ_A001 ATCSZ_B001 ATCSZ_C001 ATCSZ_D001 ATCSZ_E001
		 * ATCSZ_F001 ATCSZ_C002 ATCSZ_E002 ATCSZ_GXH ATCSZ_XCpoint ATCSZ_WLTpoint
		 */
		File fileA = new File(currentPath + "A001.txt");
		File fileB = new File(currentPath + "B001.txt");
		File fileC = new File(currentPath + "C001.txt");
		File fileD = new File(currentPath + "D001.txt");
		File fileE = new File(currentPath + "E001.txt");
		File fileF = new File(currentPath + "F001.txt");
		File fileC2 = new File(currentPath + "C002.txt");
		File fileE2 = new File(currentPath + "E002.txt");
		File fileGXH = new File(currentPath + "H001.txt");//特殊账单个性化数据文件
		File fileGxh = new File(currentPath + "Gxh.txt");//普通账单个性化数据文件
		File fileX = new File(currentPath + "G001.txt");//携程积分
		File fileW = new File(currentPath + "G002.txt");//万里通积分
		String inSR = null;
		String str[] = null;
		BufferedReader br = null;
		List<String> list;
		int num;
		
		//普通账单个性化数据文件解析
		if(fileGxh.exists()) {
			br = new BufferedReader(new FileReader(fileGxh));
			while ((inSR = br.readLine()) != null){
				if(28 == inSR.length()) {
					num = cbDao.updGxh(inSR);
					if(num != 0) {
						log.error("Gxh update error: StrContent="+inSR);
						this.returnMsg("个性化数据错误，不能解析！");
						return null;
					}else{
						log.error("Gxh String length error: Length="+inSR.length());
						this.returnMsg("个性化数据错误，不能解析！");
						return null;
					}
				}
			}
		}
		//特殊账单数据文件的解析
		if (!fileA.exists() || (!fileB.exists() && !fileD.exists())) {
			this.returnMsg("必要数据文件不全，不能导入！");
			return null;
		}
			// 解析A001
			br = new BufferedReader(new FileReader(fileA));
			while ((inSR = br.readLine()) != null) {
				list = StringUtil.SplieASCII(inSR);
				if (54 == list.size()) {
					num = cbDao.insertCustomerBill(list,person.getId());
					if (num != 0) {
						log.error("A001 insert error: Acctnbr="+list.get(2));
						this.returnMsg("A001数据错误，不能导入！");
						return null;
					}
				}else{
					log.error("A001 list size error: Size="+list.size());
					this.returnMsg("A001数据错误，不能导入！");
					return null;
				}
			}
			makeXmlDao.Proce_bill_update_city();
			makeXmlDao.Proce_bill_update_point();
			br.close();
			fileA.delete();
			// 解析B001
			if (fileB.exists()) {
				br = new BufferedReader(new FileReader(fileB));
				while ((inSR = br.readLine()) != null) {
					list = StringUtil.SplieASCII(inSR);
					if (25 == list.size()) {
						num = cbDao.insertRMBBill(list);
						if (num != 0) {
							log.error("B001 insert error: Acctnbr="+list.get(2));
							this.returnMsg("B001数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("B001 list size error: Size="+list.size());
						this.returnMsg("B001数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileB.delete();
			}
			// 解析C001
			if (fileC.exists()) {
				br = new BufferedReader(new FileReader(fileC));
				while ((inSR = br.readLine()) != null) {
					list = StringUtil.SplieASCII(inSR);
					if (17 == list.size()) {
						num = cbDao.insertRMBDetailBill(list);
						if (num != 0) {
							log.error("C001 insert error: Acctnbr="+list.get(2));
							this.returnMsg("C001数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("C001 list size error: Size="+list.size());
						this.returnMsg("C001数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileC.delete();
			}
			// 解析D001
			if (fileD.exists()) {
				br = new BufferedReader(new FileReader(fileD));
				while ((inSR = br.readLine()) != null) {
					list = StringUtil.SplieASCII(inSR);
					if (24 == list.size()) {
						num = cbDao.insertDollarBill(list);
						if (num != 0) {
							log.error("D001 insert error: Acctnbr="+list.get(2));
							this.returnMsg("D001数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("D001 list size error: Size="+list.size());
						this.returnMsg("D001数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileD.delete();
			}
			
			// 解析E001
			if (fileE.exists()) {
				br = new BufferedReader(new FileReader(fileE));
				while ((inSR = br.readLine()) != null) {
					list = StringUtil.SplieASCII(inSR);
					if (16 == list.size()) {
						num = cbDao.insertDollarDetailBill(list);
						if (num != 0) {
							log.error("E001 insert error: Acctnbr="+list.get(2));
							this.returnMsg("E001数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("E001 list size error: Size="+list.size());
						this.returnMsg("E001数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileE.delete();
			}
			// 解析F001
			if (fileF.exists()) {
				br = new BufferedReader(new FileReader(fileF));
				while ((inSR = br.readLine()) != null) {
					list = StringUtil.SplieASCII(inSR);
					if (11 == list.size()) {
						num = cbDao.insertPurchase(list);
						if (num != 0) {
							log.error("F001 insert error: Acctnbr="+list.get(2));
							this.returnMsg("F001数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("F001 list size error: Size="+list.size());
						this.returnMsg("F001数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileF.delete();
			}
			// 解析C002
			if (fileC2.exists()) {
				br = new BufferedReader(new FileReader(fileC2));
				while ((inSR = br.readLine()) != null) {
					list = StringUtil.SplieASCII(inSR);
					if (12 == list.size()) {
						num = cbDao.insertCardRMB(list);
						if (num != 0) {
							log.error("C002 insert error: Acctnbr="+list.get(2));
							this.returnMsg("C002数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("C002 list size error: Size="+list.size());
						this.returnMsg("C002数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileC2.delete();
			}
			// 解析E002
			if (fileE2.exists()) {
				br = new BufferedReader(new FileReader(fileE2));
				while ((inSR = br.readLine()) != null) {
					list = StringUtil.SplieASCII(inSR);
					if (12 == list.size()) {
						num = cbDao.insertCardDollar(list);
						if (num != 0) {
							log.error("E002 insert error: Acctnbr="+list.get(2));
							this.returnMsg("E002数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("E002 list size error: Size="+list.size());
						this.returnMsg("E002数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileE2.delete();
			}
			//解析携程积分信息
			if(fileX.exists()) {
				br = new BufferedReader(new FileReader(fileX));
				while ((inSR = br.readLine()) != null) {
					str = inSR.split("\\|\\*\\|");
					if(24 == str.length) {
						num = cbDao.insertXC(str);
						if (num != 0) {
							log.error("G001 insert error: Cardportid="+str[0]);
							this.returnMsg("积分数据错误，不能导入！");
							return null;
						}
					}else{
						log.error("G001 list size error: Size="+str.length);
						this.returnMsg("积分数据错误，不能导入！");
						return null;
					}
				}
				br.close();
				fileX.delete();
			}
			//解析万里通积分
			if(fileW.exists()) {
				br = new BufferedReader(new FileReader(fileW));
				while ((inSR = br.readLine()) != null) {
					str = inSR.split("\\|\\*\\|");
					if(8 == str.length) {
						num = cbDao.insertWLT(str);
						if (num != 0) {
							log.error("G002 insert error: Ecifno="+str[0]);
							this.returnMsg("万里通积分数据错误，不能解析！");
							return null;
						}
					}else{
						log.error("G002 list size error: Length="+str.length);
						this.returnMsg("万里通积分数据错误，不能解析！");
						return null;
					}
				}
				br.close();
				fileW.delete();
			}
			// 解析特殊账单个性化信息
			if (fileGXH.exists()) {
				br = new BufferedReader(new FileReader(fileGXH));
				while ((inSR = br.readLine()) != null) {
					if (28 == inSR.length()) {
						num = cbDao.updGXH(inSR);
						if (num != 0) {
							log.error("H001 update error: StrContent="+inSR);
							this.returnMsg("个性化数据错误，不能解析！");
							return null;
						}
					}else{
						log.error("H001 String length error: Length="+inSR.length());
						this.returnMsg("个性化数据错误，不能解析！");
						return null;
					}
				}
				br.close();
				fileGXH.delete();
			}
			
		return null;
	}
	
//	/**
//		已经移至workAction中
//	 * 生成XML文件、合成账单
//	 * @return
//	 */
//	public String make_composeXml() {
//		HashMap<String, String> map = new HashMap<String, String>();
//		request = ServletActionContext.getRequest();
//		response = ServletActionContext.getResponse();
//		Object obj = request.getSession().getAttribute("login");
//		if (null == obj)
//			return null;
//		Person person = (Person) obj;
//		if(null != filename){
//			map.put("fileName", filename);	
//			try {
//				String type = makeComposeService.makeCompose1(filename);
//				this.returnMsg(type);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}else{	//特殊账单合成
//			map.put("personNo", person.getId());
//			//生成XML
//			makeXmlService.make(person.getId());
//			try {
//				makeComposeService.makeCompose(person.getId());
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//		return null;
//	}

	// 退件文件上传
	public String backLetter() {
		response = ServletActionContext.getResponse();
		BufferedReader br = null;
		String str = "";
		BackLetter lb = new BackLetter();
		String errormessage = "";
		try {

			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					file.getPath())));
			String[] letterArray;
			// 操作日期
			Date date1 = new Date();
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
			String sPrintTime = format1.format(date1);
			int lnum = 1;
			List<BackLetter> bllist;
			while ((str = br.readLine()) != null) {
				letterArray = str.split(",");
				if (letterArray.length == 4) {
					// 验证条形码
					// 验证退信原因编号
					if (!haveCN(letterArray[1])
							&& letterArray[1].length() == 24
							&& letterArray[2].matches("\\d")) {
						lb.setFbar(letterArray[1]);
						bllist = letterService.queryBackLetter(lb);
						if (bllist == null || bllist.size() < 1) {
							lb.setFoperDate(sPrintTime);
							lb.setFbackReason(letterArray[2]);
							letterService.addBackLetter(lb);
						} else {
							errormessage = errormessage + "条形码重复，请核实文件中第"
									+ lnum + "行内容！";
						}
					} else {
						errormessage = errormessage + "条形码和原因编号验证不通过，请验证文件中第"
								+ lnum + "行条形码和原因编号的内容！";
					}
				} else {
					errormessage = errormessage + "数据给予不全，请核实文件中第" + lnum
							+ "行内容！";
				}
				lnum++;
			}
			errormessage="{success:true,msg:'"+errormessage+"'}";
			this.returnMsg(errormessage);
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (null != br)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
				log.error(e.getMessage());
			}
		}
		return SUCCESS;
	}

	/**
	 * 判断中文内容
	 * 
	 * @serialData 2011年2月24日10:21:42
	 * @author quany
	 * @param args
	 */
	public boolean haveCN(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (str.substring(i, i + 1).matches("[\\u4e00-\\u9fa5]+"))
				return true;
		}
		return false;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void setFile(File file) {
		this.file = file;
	}
	
	private void returnMsg(String msg){
		response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.print(msg);
			pw.flush();
			pw.close();
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}
	
}
